package com.dhu.stylefit.model;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VrTry {
    public static String executePythonScript(String personImageUrl, String topGarmentUrl, String bottomGarmentUrl) {
        String scriptPath = "src/main/resources/scripts/vr_tryon.py";
        ProcessBuilder processBuilder = new ProcessBuilder(
                "python", scriptPath, personImageUrl, topGarmentUrl, bottomGarmentUrl);

        // 设置环境变量，指定编码为UTF-8
        Map<String, String> env = new HashMap<>(processBuilder.environment());
        env.put("LANG", "en_US.UTF-8");
        processBuilder.environment().putAll(env);

        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));

            List<String> res=new ArrayList<>();
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("http://")) {
                    return line;
                } else if (line.contains("任务失败")) {
                    System.err.println("任务失败");
                    return null;
                }
                System.out.println(line);
                res.add(line);
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                System.err.println("Python脚本执行失败，退出码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String personImageUrl = "https://shenhuixaioliweb1.oss-cn-shanghai.aliyuncs.com/test1.jpg";
        String topGarmentUrl = "https://shenhuixaioliweb1.oss-cn-shanghai.aliyuncs.com/trousers/00b103dcb618d22c6c89204f442ce9df.jpg";
        String bottomGarmentUrl = "https://shenhuixaioliweb1.oss-cn-shanghai.aliyuncs.com/1d1a97f8-32fb-4641-aecb-a23fa09b8476.jpg";

        String imageUrl = executePythonScript(personImageUrl, topGarmentUrl, bottomGarmentUrl);
        if (imageUrl != null) {
            System.out.println("结果图片地址: " + imageUrl);
        }
    }
}
